import fs from "fs";
import dotenv from "dotenv";
import { DataSource, DataSourceOptions } from "typeorm";

export function getEnv(env: string) {
    if (fs.existsSync(env)) {
        return dotenv.parse(fs.readFileSync(env))
    }
}

export function builderConnectionOptions() {
    const defaultConfig = getEnv('.env')
    const envConfig = getEnv(`.env.${process.env.NODE_ENV || 'dev'}`)
    const config = { ...defaultConfig, ...envConfig }
    return {
        type: config['DB_TYPE'],
        username: config['DB_USERNAME'],
        password: config['DB_PASSWORD'],
        host: config['DB_HOST'],
        port: config['DB_PORT'],
        database: config['DB_DATABASE'],
        synchronize: Boolean(config['DB_SYNC']),
        autoLoadEntities: Boolean(config['DB_AUTOLOAD']),
        entities: [__dirname + '/**/*.entity{.ts,.js}'],
        retryDelay: 500,
        retryAttempts: 10,
    } as DataSourceOptions
}

export default new DataSource({
    ...builderConnectionOptions()
} as DataSourceOptions)